<!-- #layout name=blank -->
<div id="app">
  <div class="page-header">
    <h1 class="title">Files</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a @click="showNewFolderModal=true" class="btn green navbar-btn"
        >New folder</a
      >
      <a href="javascript:;" class="btn green navbar-btn btn-file"
        ><span>Upload files</span>
        <input
          type="file"
          multiple
          v-kb-upload="{
            allowMultiple: true,
            acceptTypes: ['*/*'],
            callback: uploadFile
        }"
        />
      </a>
      <a
        class="btn red navbar-btn"
        v-show="selectedRows.length"
        @click="onDelete"
        >Delete</a
      >
    </div>
  </div>
  <div class="page-bar" v-if="crumbPath">
    <ol class="breadcrumb">
      <template v-for="(item,index) in crumbPath">
        <li :key="index" v-if="index != crumbPath.length-1">
          <a href="javascript:;" @click="onChoosingFolder(item.fullPath)"
            >{{ item.name }}</a
          >
        </li>
        <li v-if="index == crumbPath.length-1" class="active" :key="index"
          >{{ item.name }}</li
        >
      </template>
    </ol>
  </div>
  <div class="table-responsive">
    <table class="table table-striped table-hover">
      <thead>
        <tr>
          <th class="table-checkbox">
            <input
              type="checkbox"
              v-model="selectAll"
              :disabled="folders.length+files.length==0"
            />
          </th>
          <th>URL</th>
          <th>Used by</th>
          <th>Size</th>
          <th>Last modified</th>
          <th class="table-action">Preview</th>
        </tr>
      </thead>
      <tbody v-if="(folders.length+files.length)>0">
        <tr
          v-for="folder in folders"
          :key="folder.fullPath"
          @click="folder.selected=!folder.selected"
        >
          <td><input v-model="folder.selected" type="checkbox"/></td>
          <td>
            <a @click="onChoosingFolder(folder.fullPath)" href="javascript:;">
              <i class="table-icon fa fa-folder"></i>
              {{ folder.fullPath }}
            </a>
          </td>
          <td>-</td>
          <td>{{ folder.size || "-" }}</td>
          <td>{{new Date(folder.lastModified).toDefaultLangString()}}</td>
          <td></td>
        </tr>
        <tr
          v-for="file in files"
          :key="file.id"
          @click="file.selected=!file.selected"
        >
          <td>
            <input type="checkbox" v-model="file.selected" />
          </td>
          <td>{{ file.url }}</td>
          <td>
            <template v-if="Object.keys(file.relations).length">
              <a
                v-for="refer in Object.keys(file.relations)"
                href="javascript:;"
                class="label label-sm kb-table-label-refer"
                @click.stop="getRelation(file.id,refer)"
                :style="{background:Kooboo.getLabelColor(refer)}"
                >{{ file.relations[refer] + " " +
                Kooboo.text.component.table[refer.toLowerCase()] }}</a
              >
            </template>
            <template v-else>
              -
            </template>
          </td>
          <td>{{ Kooboo.bytesToSize(file.size || "-") }}</td>
          <td>
            {{new Date(file.lastModified).toDefaultLangString()}}
          </td>
          <td>
            <a
              class="btn blue"
              target="_blank"
              @click.stop=""
              :href="file.previewUrl"
              >Preview</a
            >
          </td>
        </tr>
      </tbody>
      <tbody v-else>
        <tr>
          <td class="text-center" colspan="100">Empty</td>
        </tr>
      </tbody>
    </table>
  </div>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showNewFolderModal"
  >
    <div class="modal-dialog" v-if="showNewFolderModal">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">New folder</h4>
        </div>
        <div class="modal-body">
          <kb-form :model="model" :rules="rules" ref="form">
            <kb-form-item prop="folderName">
              <label class="col-md-3 control-label">Name</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="model.folderName"
                />
              </div>
            </kb-form-item>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button @click="onNewFolderModalSubmit" class="btn green"
            >Save</button
          >
          <button data-dismiss="modal" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>

  <kb-relation-modal></kb-relation-modal>
</div>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbForm.js",
    "/_Admin/Scripts/components/kbRelationModal.js"
  ]);

  new Vue({
    el: "#app",
    data: function() {
      var self = this;
      return {
        breads: [
          {
            name: "SITES"
          },
          {
            name: "DASHBOARD"
          },
          {
            name: Kooboo.text.common.Files
          }
        ],
        showNewFolderModal: false,
        crumbPath: [],
        folders: [],
        files: [],
        model: {
          folderName: ""
        },
        rules: {
          folderName: [
            { required: Kooboo.text.validation.required },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64
            },
            {
              pattern: /^([a-zA-Z\w\-\.])*$/,
              message: Kooboo.text.validation.folderNameInvalid
            },
            {
              validate: function(value) {
                return self.folders.every(function(e) {
                  return e.name != value.trim();
                });
              },
              message: Kooboo.text.validation.taken
            }
          ]
        }
      };
    },
    mounted: function() {
      this.onChoosingFolder(location.hash ? location.hash.split("#")[1] : "");
    },
    computed: {
      selectAll: {
        get: function() {
          return (
            this.folders.every(function(folder) {
              return folder.selected;
            }) &&
            this.files.every(function(file) {
              return file.selected;
            }) &&
            this.folders.length + this.files.length > 0
          );
        },
        set: function(value) {
          this.folders.forEach(function(folder) {
            folder.selected = value;
          });
          this.files.forEach(function(file) {
            file.selected = value;
          });
        }
      },
      selectedRows: function() {
        return this.folders
          .filter(function(folder) {
            return folder.selected;
          })
          .concat(
            this.files.filter(function(file) {
              return file.selected;
            })
          );
      }
    },
    methods: {
      onNewFolderModalSubmit: function() {
        var self = this;
        if (this.$refs.form.validate()) {
          Kooboo.File.createFolder({
            path: self.crumbPath[self.crumbPath.length - 1].fullPath,
            name: self.model.folderName
          }).then(function(res) {
            if (res.success) {
              self.onChoosingFolder(
                location.hash ? location.hash.split("#")[1] : ""
              );
              self.showNewFolderModal = false;
            }
          });
        }
      },
      uploadFile: function(data, files) {
        var me = this;
        function upload() {
          var folders = _.cloneDeep(me.crumbPath);
          data.append("folder", folders.reverse()[0].fullPath);

          Kooboo.Upload.File(data).then(function(res) {
            if (res.success) {
              me.onChoosingFolder(folders[0].fullPath);
            }
          });
        }

        if (!Kooboo.isFileNameExist(files, me.files)) {
          upload();
        } else {
          if (confirm(Kooboo.text.confirm.overrideFile)) {
            upload();
          }
        }
      },
      getRelation: function(id, by) {
        Kooboo.EventBus.publish("kb/relation/modal/show", {
          id: id,
          by: by,
          type: "CmsFile"
        });
      },
      onDelete: function() {
        var me = this;
        if (confirm(Kooboo.text.confirm.deleteItems)) {
          var folders = [],
            files = [];

          _.forEach(me.selectedRows, function(selected) {
            if (selected.type == "folder") {
              folders.push(selected.fullPath);
            } else if (selected.type == "file") {
              files.push(selected.id);
            }
          });

          Kooboo.File.deleteFolders(JSON.stringify(folders)).then(function(
            res
          ) {
            if (res.success) {
              Kooboo.File.deleteFiles(JSON.stringify(files)).then(function(r) {
                if (r.success) {
                  me.onChoosingFolder(
                    location.hash ? location.hash.split("#")[1] : ""
                  );
                  window.info.done(Kooboo.text.info.delete.success);
                } else {
                  window.info.done(Kooboo.text.info.delete.fail);
                }
              });
            }
          });
        }
      },
      onChoosingFolder: function(path) {
        var me = this;
        Kooboo.File.getList({
          path: path
        }).then(function(res) {
          if (res.success) {
            me.crumbPath = res.model.crumbPath;

            if (res.model.folders) {
              me.folders = res.model.folders.map(function(folder) {
                folder.type = "folder";
                folder.selected = false;
                return folder;
              });
            } else me.folders = [];

            if (res.model.files) {
              me.files = res.model.files.map(function(file) {
                file.type = "file";
                file.selected = false;
                return file;
              });
            } else me.file = [];

            location.hash = path;
          }
        });
      }
    },
    watch: {
      showNewFolderModal: function(value) {
        if (!value) {
          this.model.folderName = "";
        }
      }
    }
  });
</script>
